import {
    ProFormInstance,
    ProFormText,
    ProFormRadio,
    StepsForm,
    ProFormSelect,
    ProFormTreeSelect,
} from '@ant-design/pro-components';
import { useEffect, useRef } from 'react';
import { Button, Modal, message, Select, TreeSelect, Table, Popconfirm, Tree, Tag } from 'antd';
import { addRole, getRoleDetail, getRoleList, editRole, deleteRole, updateRoleStatus } from 'apis/role';
import { getOrgTree, getMenuTree, getRoleList as getRoleListByOrg } from 'apis/common';
import React, { useState } from 'react';

const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true);
        }, time);
    });
};

export default (props):JSX.Element => {
    // 新增弹框
    const { visible, setVisible, refresh } = props;
    // 步骤
    const [current, setCurrent] = useState(0);

    const onCurrentChange = (value) => {
        console.log(value);
        setCurrent(value);
        if (value === 1) {
            console.log(formRef?.current?.getFieldValue());
        }
    };
    // 数据权限类型
    const [dataScope, setDataScope] = useState(undefined);
    // 本级以上勾选权限
    const [dataScopeOrg, setDataScopeOrg] = useState(undefined);
    // 自定义勾选权限
    const [dataScopeOrgs, setDataScopeOrgs] = useState([]);

    // 组织
    const [org, setOrg] = useState(undefined);
    const [orgTree, setOrgTree] = useState([]);

    // 菜单
    const [menu, setMenu] = useState([]);
    const [menuTree, setMenuTree] = useState([]);

    // 常用角色
    const [roleList, setRoleList] = useState([]);

    // 表单
    const formRef = useRef<ProFormInstance>();

    const formItemLayout = {
        labelCol: {
            span: 6,
        },
        wrapperCol: {
            span: 18,
        },
    };

    const handleCancel = () => {
        setCurrent(0);
        setOrg(undefined);
        setDataScope(undefined);
        setVisible(false);
    };

    // 初始化数据
    // const { currentTenant } = useTokenStore();
    useEffect(() => {
        getOrgTree({}).then((res) => {
            console.log(res);
            setOrgTree([res.organizationTree]);
            if (props?.organizationId && visible) {
                getRoleListByOrg({ organizationId: props?.organizationId }).then((res) => {
                    setRoleList(res.recordDatas);
                });
                formRef.current?.setFieldValue('organizationId', props?.organizationId);
            }
        });
        setMenuTree([]);
        getMenuTree({}).then((res) => {
            if (res.menuTree) {
                // res.menuTree.disabled = true;
                res.menuTree.checkable = false;
                setMenuTree([res.menuTree]);
            }
        });
    }, [visible]);

    return (
        <>
            <StepsForm
                onFinish={async (data) => {
                    let flag = true;
                    if (dataScope === 3) {
                        if (!dataScopeOrg) {
                            message.warning('请选择顶级节点');
                            flag = false;
                        } else {
                            data.dataScopeId = dataScopeOrg;
                        }
                    }
                    if (dataScope === 1) {
                        if (dataScopeOrgs.length === 0) {
                            message.warning('请至少选择一个节点');
                            flag = false;
                        } else {
                            data.customDataScopeOrgIds = dataScopeOrgs;
                        }
                    }
                    if (flag) {
                        data.authMenus = menu;
                        addRole(data).then((res) => {
                            // await waitTime(1000);
                            setCurrent(0);
                            setOrg(undefined);
                            setDataScope(undefined);
                            setVisible(false);
                            refresh();
                            message.success('角色创建成功');
                        });
                    }
                }}
                current={current}
                onCurrentChange={onCurrentChange}
                formProps={{
                    validateMessages: {
                        required: '此项为必填项',
                    },
                }}
                submitter={{
                    render: (props) => {
                        if (props.step === 0) {
                            return (
                                <>
                                    <Button type='primary' onClick={() => props.onSubmit?.()}>
                                        下一步
                                    </Button>
                                    ,
                                </>
                            );
                        }

                        if (props.step === 1) {
                            return [
                                <Button key='pre' onClick={() => props.onPre?.()}>
                                    上一步
                                </Button>,
                                <Button type='primary' onClick={() => props.onSubmit?.()}>
                                    完成
                                </Button>,
                            ];
                        }
                    },
                }}
                stepsFormRender={(dom, submitter) => {
                    return (
                        <Modal
                            title='创建角色'
                            centered
                            zIndex={50}
                            styles={{ body: { marginTop: '40px', marginBottom: '40px' } }}
                            width={1300}
                            onCancel={handleCancel}
                            open={visible}
                            footer={submitter}
                            destroyOnClose
                        >
                            {dom}
                        </Modal>
                    );
                }}
            >
                <StepsForm.StepForm
                    name='base'
                    layout='horizontal'
                    {...formItemLayout}
                    formRef={formRef}
                    title='填写基本信息'
                    onFinish={async () => {
                        // await waitTime(500);
                        console.log('第一步完成');
                        if (menu.length === 0) {
                            message.warning('请至少选择一个菜单节点');
                            return false;
                        }
                        return true;
                    }}
                >
                    <div style={{ width: '1200px', display: 'flex' }}>
                        <div style={{ width: '50%', marginTop: '50px' }}>
                            <ProFormText
                                name='name'
                                label='角色名称'
                                placeholder='请输入角色名称'
                                fieldProps={{ maxLength: 18 }}
                                rules={[{ required: true }]}
                            />
                            <ProFormText
                                name='roleKey'
                                label='角色标识'
                                placeholder='请输入角色标识'
                                fieldProps={{ maxLength: 18 }}
                                rules={[{ required: true }]}
                            />
                            <ProFormTreeSelect
                                disabled={!!props?.organizationId}
                                label='所属组织'
                                name='organizationId'
                                rules={[{ required: true }]}
                                onChange={(value) => {
                                    setOrg(value);
                                    if (value) {
                                        getRoleListByOrg({ organizationId: value }).then((res) => {
                                            setRoleList(res.recordDatas);
                                        });
                                    }
                                }}
                                fieldProps={{
                                    fieldNames: { label: 'name', value: 'id' },
                                    treeData: orgTree,
                                    allowClear: false,
                                    treeDefaultExpandAll: true,
                                    placeholder: '请选择所属组织',
                                }}
                            />

                            <ProFormSelect
                                options={roleList}
                                disabled={!org && !props?.organizationId}
                                onChange={(value, data) => {
                                    console.log(value, data);
                                    if (value) {
                                        if (data.authMenus) {
                                            let tree = new Set(menu.concat(data.authMenus));
                                            console.log([...tree], data.authMenus);
                                            setMenu([...tree]);
                                        }
                                        message.success('模板权限填充完成');
                                    }
                                }}
                                name='roleTem'
                                label='组织角色模板'
                                fieldProps={{
                                    fieldNames: { label: 'name', value: 'id' },
                                }}
                                placeholder='请选择角色模板快捷勾选菜单'
                            />
                        </div>
                        <div style={{ width: '50%', padding: '0 20px', textAlign: 'center' }}>
                            <div style={{ color: 'black', fontWeight: 'bold', fontSize: '15px', marginBottom: '10px' }}>
                                菜单和按钮选择(已选{menu.length}个)
                            </div>

                            <div style={{ paddingLeft: '80px', paddingTop: '10px', height: '50vh', overflow: 'auto' }}>
                                {menuTree.length > 0 ? (
                                    <Tree
                                        titleRender={(nodeData) => {
                                            return (
                                                <div>
                                                    {nodeData.module === 1 || nodeData.module === 2 ? (
                                                        <Tag color={nodeData.module === 1 ? 'blue' : 'success'}>
                                                            {nodeData.module === 1 ? 'PC' : '移动'}
                                                        </Tag>
                                                    ) : null}

                                                    {nodeData.label}

                                                    {(nodeData.type == 1 || nodeData.type == 2) && (
                                                        <Tag color='purple' className='ml-4px'>
                                                            页面
                                                        </Tag>
                                                    )}

                                                    {nodeData.type == 3 && (
                                                        <Tag color='cyan' className='ml-4px'>
                                                            按钮
                                                        </Tag>
                                                    )}
                                                </div>
                                            );
                                        }}
                                        selectable={false}
                                        checkable
                                        checkedKeys={menu}
                                        onCheck={(value) => {
                                            setMenu(value);
                                        }}
                                        fieldNames={{ title: 'label', key: 'id' }}
                                        defaultExpandAll
                                        treeData={menuTree}
                                    />
                                ) : (
                                    <div style={{ marginTop: '30px' }}>数据加载中......</div>
                                )}
                            </div>
                        </div>
                    </div>
                </StepsForm.StepForm>
                <StepsForm.StepForm name='dataPower' title='数据权限配置'>
                    <div className='w-[640px]'>
                        <ProFormRadio.Group
                            label='选择数据类型'
                            name='dataScope'
                            onChange={(t) => setDataScope(t.target.value)}
                            rules={[{ required: true }]}
                            options={[
                                { label: '自定义', value: 1 },
                                { label: '本级', value: 2 },
                                { label: '本级及以上', value: 3 },
                                { label: '本级及以下', value: 4 },
                            ]}
                        />
                        {dataScope == 3 ? (
                            <div style={{ height: '240px', overflow: 'auto' }}>
                                <Tree
                                    onSelect={(value) => {
                                        console.log(value);
                                        setDataScopeOrg(value[0]);
                                    }}
                                    fieldNames={{ title: 'name', key: 'id' }}
                                    defaultExpandAll
                                    checkStrictly
                                    treeData={orgTree}
                                />
                            </div>
                        ) : (
                            ''
                        )}
                        {dataScope == 1 ? (
                            <div style={{ height: '240px', overflow: 'auto' }}>
                                <Tree
                                    checkable
                                    selectable={false}
                                    onCheck={(value) => setDataScopeOrgs(value)}
                                    fieldNames={{ title: 'name', key: 'id' }}
                                    defaultExpandAll
                                    treeData={orgTree}
                                    checkedKeys={dataScopeOrgs}
                                />
                            </div>
                        ) : (
                            ''
                        )}
                    </div>
                </StepsForm.StepForm>
            </StepsForm>
        </>
    );
};
